import React, {Component} from 'react'
import UserRouter from '../index'
import {get, queryParse} from '../../../common/js/utils'
import {connect} from 'react-redux'
import {Page} from '../../../component/pagination'
import {Reply} from './reply'
import {List} from 'antd'
import {withRouter} from 'react-router-dom'

function mapStateToProps(state, props) {
  return {
    userInfo: state.get('userInfo')
  }
}

@withRouter
@connect(mapStateToProps)
class Replies extends Component {

  page = 0
  size = 10

  state = {
    list: [],
    total: 0,
    loading: false
  }

  onPageChange = (page, size) => {
    this.page = page - 1
    this.size = size
    this.getList()
  }

  getList = async () => {
    const res = await get('/api/users/myReplies', {
      page: this.page,
      size: this.size,
      _id: this.search._id || ''
    }, loading => this.setState({loading}))
    if (res.result === 1) {
      this.currentSize = res.data.length
      this.setState({
        list: res.data,
        total: res.total
      })
    }
  }

  onDel = () => {
    this.setState({
      total: this.state.total - 1
    })
    this.currentSize--
    if (this.currentSize === 0) {
      if (this.page > 0) {
        this.page--
      }
      this.getList()
    }
  }

  componentWillMount() {
    this.search = queryParse(this.props.location.search)
    this.getList()
  }

  render() {
    const {list, total, loading} = this.state

    return (
      <UserRouter>
        <List
          itemLayout="horizontal"
          dataSource={list}
          loading={loading}
          renderItem={item => (
            <Reply
              item={item}
              onDel={this.onDel}
            />
          )}
        />
        <Page
          size={this.size}
          total={total}
          onChange={this.onPageChange}
        />
      </UserRouter>
    )
  }
}

export default Replies
